package com.longcai.cm.moudules.system.utils;

import com.alibaba.fastjson.JSON;
import com.longcai.cm.exception.SysRuntimeException;
import com.longcai.cm.moudules.system.domain.SysUsers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Collection;
import java.util.List;

public class ShiroUtils {

    @Resource
    private static SessionDAO sessionDAO;

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static SysUsers getUser() {
        Object principal = getSubject().getPrincipal();
        if (principal == null) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(principal), SysUsers.class);
    }

    public static String getUserId() {
        SysUsers user = getUser();
        if (user == null) {
            throw new SysRuntimeException("登录已超时");
        }
        return user.getId();
    }

    public static String getUserName() {
        SysUsers user = getUser();
        if (user == null) {
            return null;
        }
        return user.getUsername();
    }

    public static List<Principal> getPrinciples() {
        List<Principal> principals = null;
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        return principals;
    }

}
